package ca

import (
	"fmt"
	"github.com/cihub/seelog"
	"github.com/robfig/cron"
	"io/ioutil"
	"myFtp/conf"
	"myFtp/influxdb"
	"os"
	"time"
)

func RunFunc() {
	c := cron.New()
	myCron := conf.GetCron()
	c.AddFunc(myCron.ExectNotSuccessCron, func() {
		seelog.Infof(fmt.Sprintf("exect not success %v\n", myCron.ExectNotSuccessCron))
		ExectNotSuccess()
	})
	c.AddFunc(myCron.DeleteFileCron, func() {
		seelog.Infof(fmt.Sprintf("delete file cron %v\n", myCron.DeleteFileCron))
		deleteFile()
		checkFileCount(myCron.FileMaxCount, myCron.SubTime)
	})
	c.Start()
	seelog.Infof("cron %+v\n", myCron)
}

func checkFileCount(maxCount, subTime int) {
	ftpConf := conf.FtpConf()
	fileInfl, err := ioutil.ReadDir(ftpConf.Dir)
	if err != nil {
		seelog.Error(err)
	} else {
		fileCount := len(fileInfl)

		if fileCount > maxCount {
			nt := time.Now()
			for _, file := range fileInfl {
				if !file.IsDir() {
					su := nt.Sub(file.ModTime()).Minutes()
					if su > float64(subTime) {
						seelog.Infof("checkFileCount %v %v\n", file.Name(), file.ModTime())
						removeFile(fmt.Sprintf("%v/%v", ftpConf.Dir, file.Name()))
					}
				}
			}
		}
	}
}

func deleteFile() {
	files := conf.InfluxdbConnect().SelectFtpFileByStauts(influxdb.FTPFILE, 0)
	seelog.Infof("delete File len:%v\n", len(files))
	for _, val := range files {
		if len(val.FileName) == 0 {
			val.Status = 1
		} else {
			wp := fmt.Sprintf("%v%v", conf.FtpConf().Dir, val.FileName)
			seelog.Infof("delete file path:%v\n", wp)
			exist := PathExist(wp)
			if exist {
				val.Status = removeFile(wp)
			} else {
				val.Status = 1
			}
		}
	}

	conf.InfluxdbConnect().GroupInsertFtpFile(files, influxdb.FTPFILE)

}

func removeFile(wp string) int {
	err := os.Remove(wp)
	if err == nil || os.IsNotExist(err) {
		return 1
	} else {
		seelog.Error(err.Error())
		return 0
	}
}
func PathExist(_path string) bool {
	_, err := os.Stat(_path)
	if err != nil && os.IsNotExist(err) {
		return false
	}
	return true
}
